<?php

class Creatix_Pager_Layout extends Doctrine_Pager_Layout
{

	public function __construct($pager, $pagerRange, $urlMask)
	{

		parent::__construct($pager, $pagerRange, $urlMask);

		$this->setTemplate('<a href="{%url}?pg_num={%page_number}">{%page}</a>');
		$this->setSelectedTemplate('<b>{%page}</b>');
		$this->setSeparatorTemplate(', ');
	}

	public function display($options = array(), $return = false)
	{
		$pager = $this->getPager();

		if ($pager->haveToPaginate())
		{
			$str = '';

			if( $pager->getLinkStyle() == 'ajax')
			{
				$this->setTemplate( urldecode( jq_link_to_remote( '{%page}', array(
													'nourlfor' => ($options['nourl']),
													'url'=> '{%url}?pg_num={%page_number}',
													'update'   => $pager->getAjaxDivUpdate()
												))));
			}

			// First page
			$this->addMaskReplacement('page', 'Primeiro', true);
			$options['page_number'] = $pager->getFirstPage();
			$str .= '[ ' . $this->processPage($options);

			// Previous page
			$this->addMaskReplacement('page', 'Anterior', true);
			$options['page_number'] = $pager->getPreviousPage();
			$str .= ' / ' . $this->processPage($options) . ' ] ';

			// Pages listing
			$this->removeMaskReplacement('page');
			$str .= parent::display($options, true);

			// Next page
			$this->addMaskReplacement('page', 'Pr&oacute;ximo', true);
			$options['page_number'] = $pager->getNextPage();
			$str .= ' [ ' . $this->processPage($options) . ' / ';

			// Last page
			$this->addMaskReplacement('page', '&Uacute;ltimo', true);
			$options['page_number'] = $pager->getLastPage();
			$str .= $this->processPage($options) . ' ] ';

			// Possible wish to return value instead of print it on screen
			if ($return) {
				return $str;
			}
			echo $str;
		}
	}

	public function getNumFirstItem(){
		$pager = $this->getPager();
		return ($pager->getMaxPerPage() * ($pager->getPage() - 1)) + 1;
	}

	public function getNumLastItem(){
		$pager = $this->getPager();
		$result = $pager->getMaxPerPage() * $pager->getPage();
		if ($result > $pager->getNumResults()){
			$result = $result - ($result - $pager->getNumResults());
		}
		return $result;
	}

	public function displayResultados(){
		if (!$this->getPager()->getNumResults()){
			echo 'Nenhum registro encontrado';
		} else {
			$s = $this->getPager()->getNumResults() == 1 ? '' : 's';

			echo $this->getPager()->getNumResults() .
           " registro$s encontrado$s";

			if ($this->getPager()->haveToPaginate()){
				echo ', mostrando ' .
				$this->getNumFirstItem() . ' a ' .
				$this->getNumLastItem();
			}
		}
	}

}

?>
